# coding=utf-8
"""
作者：董新强 
创建时间：微信相关接口
描述：2020-7-27
"""
from tornado.gen import coroutine

from apis.base_api import BaseHandler
from auth.user_manage import UserManage
from frameworks.resonse_msgs import fail
from pools import run_async
from wx.wx_user_manage import WxUserManage


class LoginWxMiniHandler(BaseHandler):
    @coroutine
    def post(self):
        if not self.validated: return self.finish(fail(msg='没有权限').response)

        try:
            result = yield WxUserManage().jscode2session(self.req_dict.get('code'))
            if not result:
                return self.finish(fail(msg='登录失败').response)

            # 登录
            wx = yield run_async(UserManage.login_with_wx_open_id, self.app_key, result['openid'])

            if not wx.is_ok():
                return self.finish(fail(msg='登录失败').response)

            self.finish(wx.response)
        except Exception as e:
            self.finish(fail(msg='服务器内部错误').response)

    def http_get(self):
        return {'status': 'success'}
